package com.xts.weinfo.ui.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.xts.weinfo.R;
import com.xts.weinfo.bean.DataBean;
import com.xts.weinfo.bean.ItInfoTabBean;
import com.xts.weinfo.widget.ItemCallBack;

import java.util.ArrayList;
import java.util.Collections;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RlvInterestAdapter extends RecyclerView.Adapter implements ItemCallBack {
    public ArrayList<DataBean> mList;

    public RlvInterestAdapter(ArrayList<DataBean> list) {

        mList = list;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_interest, parent, false);
        return new VH(inflate);
    }

    /**
     * 因为子条目会复用,为了避免条目显示错乱,一定要由数据控制界面展示
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        final DataBean bean = mList.get(position);
        VH vh = (VH) holder;
        vh.mTv.setText(bean.getName());
        vh.mSc.setChecked(bean.getIsInterested());

        //选中与否的监听
        vh.mSc.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //是否按压控件
                if (buttonView.isPressed()){
                    //说明是用户的行为,不是代码操作的
                    bean.setIsInterested(isChecked);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    class VH extends RecyclerView.ViewHolder{
        @BindView(R.id.tv)
        TextView mTv;
        @BindView(R.id.sc)
        SwitchCompat mSc;

        public VH(View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);
        }
    }

    //交换两个条目的位置
    @Override
    public void onItemMove(int fromPosition, int toPosition) {
        //交换两个索引的数据
        Collections.swap(mList,fromPosition,toPosition);
        //刷新界面,局部刷新
        notifyItemMoved(fromPosition,toPosition);
    }

    //删除某个条目
    @Override
    public void onItemDelete(int position) {
        mList.remove(position);
        notifyDataSetChanged();
    }

}
